/*
 * @Description:
 * @Author: shizhe
 * @Date: 2021-09-06 20:09:03
 * @LastEditTime: 2022-06-30 15:17:08
 * @LastEditors: shizhe
 * @Reference:
 */
//引入安装的axios插件
import axios from 'axios'
import qs from 'qs'
import router from '../router'
import { Message } from 'element-ui'
import common from '../utils/common.js'
import glo from './global'
import store from '../store/index'
import { showLoading, hideLoading } from '../components/common/loading'
const http = options => {
  let token = common.getCookie('materialsToken')
  return new Promise((resolve, reject) => {
    const defaultOptions = {}
    const newOptions = {
      ...defaultOptions,
      ...options
    }

    //headers默认传递json格式数据，这里也可以设置token，每次调用都会携带
    newOptions.headers = {
      'content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers
    }
    newOptions.headers[glo.tokenName] = token
    //这里可以在调用的时候看到你的method、url、data、headers等参数
    // console.log(newOptions);

    showLoading()
    axios({
      method: newOptions.method,
      url: glo.weburl + newOptions.url,
      data: newOptions.data,
      headers: newOptions.headers
    })
      .then(res => {
        //根据返回的状态码判断，注意res返回的并不一定都是status，比如小程序就是statusCode
        let status = parseInt(res.status)
        // console.log(res);
        switch (status) {
          case 200:
            //这里我们只需要获取返回的data中的数据即可
            if (res.data.code == '401') {
              localStorage.removeItem('userId')
              localStorage.removeItem('userName')
              localStorage.removeItem('enterpriseId')
              localStorage.removeItem('enterpriseName')
              localStorage.removeItem('biddingSwitch')
              localStorage.removeItem('enterpriseType')
              common.setCookie('materialsToken', '', 1)
              store.commit('setWhetherLogin', '')
              store.commit('setUserId', '')
              store.commit('setUserName', '')
              store.commit('setUpcoming', [])
              Message.error('请登录')
              router.push('/login')
            } else if (res.data.code == '400') {
              Message.error(res.data.data[0]['msg'])
            } else {
              resolve(res.data)
            }
            break
          case 400:
            Message.error('参数验证失败！')
            reject(res)
            break

          default:
            reject(res)
            break
        }
        hideLoading()
      })
      .catch(err => {
        hideLoading()
        Message.error('网络异常，请求失败，请稍后再试')
        reject(err)
      })
  })
}

export default http
